package com.ctsi.framework.gateway.fallback;

import com.ctsi.commons.util.json.JsonUtil;
import com.ctsi.framework.common.exception.CoreErrorConstant;
import com.ctsi.framework.common.response.UnifiedResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: zhangjw
 * @Date: 2018/7/1 16:19
 * @Description: 微服务网关统一回退处理
 */
@Component
public class UnifyFallbackProvider implements FallbackProvider {

    private static final Logger log = LoggerFactory.getLogger(UnifyFallbackProvider.class);

    /**
     * 将回退规则应用到所有路由
     * @return
     */
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        log.error("request【{}】failed，error is： {}",cause);
        return new ClientHttpResponse() {

        /**
         * 网关向api服务请求是失败了，但是消费者客户端向网关发起的请求是OK的，
         * 不应该把api的404,500等问题抛给客户端
         * 网关和api服务集群对于客户端来说是黑盒子
         * @return
         * @throws IOException
         */
         @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                UnifiedResponse<Void> response = UnifiedResponse.error(CoreErrorConstant.ERROR_CODE,"微服务不在线!");
                return new ByteArrayInputStream(JsonUtil.toJson(response).getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
    }
}

